import BaseModule from './app/base-module'

const PasswordKeyboardEvent = {
  showKeyboard(
    options = {
      title: undefined,
      needRandom: true,
      needHint: false,
      useLetter: '1', // 1 - 9宫格数字，2-字母数字，0-字母字符
      maxLength: 6,
    }
  ) {
    const command = {
      title: options.title,
      needRandom: options.needRandom,
      needHint: options.needHint,
      useLetter: options.useLetter,
      maxLength: options.maxLength,
    }
    return BaseModule.fireEventForAsync('showKeyboard', command)
  },

  /**
   * 调取支付密码录入页面
   * @param {*} params
   * @param {*} config
   * @returns Promise
   */
  getPwdInputPageForPbank(params = {}, config = {}) {
    const defaultConfig = {
      useletter: '2',
      needrandom: '1',
      title: '请输入密码',
      abstract: '',
    }
    const { useletter, needrandom, title, abstract } = Object.assign(
      defaultConfig,
      config
    )
    // eslint-disable-next-line no-async-promise-executor,consistent-return
    return new Promise(async (resolve, reject) => {
      const { timestampEnc, serverRandom } = params
      if (!timestampEnc || !serverRandom) {
        // eslint-disable-next-line no-promise-executor-return
        return reject(new Error('timestampEnc and serverRandom is required'))
      }
      BaseModule.fireEventForAsync('popPasswordInputViewThreeDesTimestamp', {
        // 时间戳
        timestamp: timestampEnc,
        // 随机数
        serverRandom,
        // 默认初始化的显示的键盘类型（1.字母、2.数字、3.字符）
        useletter,
        // 是否随机 0 标识不需要随机
        needrandom,
        // 标题
        title,
        // 摘要信息
        abstract,
      })
        .then((data) => {
          log(TAG, data)
          const isCancel = data.cancel
          const cypheredTxt = data.passwordCyphered
          const errMsg = data.err
          if (isCancel) {
            reject(new Error('关闭了取消了录入'))
          } else if (errMsg) {
            reject(new Error(errMsg))
          } else if (cypheredTxt) {
            resolve(cypheredTxt)
          } else {
            reject(new Error('获取密文失败[客户端未返回正确的结果]'))
          }
        })
        .catch((error) => {
          // TODO 全局提示
          return reject(error)
        })
    })
  }
}

export default PasswordKeyboardEvent;
